<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="showAddUserDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>
      
      <el-table :data="users" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="200">
          <template #default="scope">
            <el-tag 
              v-for="role in scope.row.roles" 
              :key="role.id" 
              size="small" 
              style="margin-right: 5px;">
              {{ role.roleName }}
            </el-tag>
            <el-button 
              size="small" 
              type="primary" 
              @click="showRoleAssignDialog(scope.row)"
              style="margin-left: 5px;">
              分配角色
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteUser(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog 
      v-model="userDialogVisible" 
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px">
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px">
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        
        <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saveLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog 
      v-model="roleAssignDialogVisible" 
      title="分配角色"
      width="600px">
      <div v-if="currentUser">
        <p><strong>用户：</strong>{{ currentUser.username }} ({{ currentUser.realName }})</p>
        <p><strong>当前角色：</strong>
          <el-tag 
            v-for="role in currentUser.roles" 
            :key="role.id" 
            size="small" 
            style="margin-right: 5px;">
            {{ role.roleName }}
          </el-tag>
        </p>
        
        <el-divider />
        
        <div>
          <p><strong>选择角色：</strong></p>
          <el-checkbox-group v-model="selectedRoleIds">
            <el-checkbox 
              v-for="role in availableRoles" 
              :key="role.id" 
              :label="role.id">
              {{ role.roleName }} - {{ role.description }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleAssignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="assignRoles" :loading="roleAssignLoading">
            确定分配
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userApi, roleApi } from '../api'

// 响应式数据
const users = ref([])
const loading = ref(false)
const userDialogVisible = ref(false)
const isEdit = ref(false)
const saveLoading = ref(false)
const userFormRef = ref()

// 角色分配相关数据
const roleAssignDialogVisible = ref(false)
const currentUser = ref(null)
const availableRoles = ref([])
const selectedRoleIds = ref([])
const roleAssignLoading = ref(false)

// 用户表单
const userForm = ref({
  id: null,
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: 1,
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载用户列表
const loadUsers = async () => {
  try {
    loading.value = true
    const response = await userApi.getUserList()
    if (response.data.code === 200) {
      users.value = response.data.data || []
    } else {
      throw new Error(response.data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error(error.message || '加载失败')
    // 使用模拟数据作为后备
    users.value = [
      {
        id: 1,
        username: 'admin',
        realName: '管理员',
        email: 'admin@example.com',
        phone: '13800138000',
        status: 1,
        createTime: '2024-01-01 00:00:00',
        roles: [
          { id: 1, roleName: '超级管理员' },
          { id: 2, roleName: '系统管理员' }
        ]
      }
    ]
  } finally {
    loading.value = false
  }
}

// 加载可用角色列表
const loadAvailableRoles = async () => {
  try {
    const response = await roleApi.getRoleList()
    if (response.data.code === 200) {
      availableRoles.value = response.data.data || []
    } else {
      throw new Error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
    // 使用模拟数据作为后备
    availableRoles.value = [
      { id: 1, roleName: '超级管理员', description: '系统最高权限' },
      { id: 2, roleName: '系统管理员', description: '系统管理权限' },
      { id: 3, roleName: '普通用户', description: '基本操作权限' }
    ]
  }
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  isEdit.value = false
  resetUserForm()
  userDialogVisible.value = true
}

// 编辑用户
const editUser = (user) => {
  isEdit.value = true
  Object.assign(userForm.value, user)
  userDialogVisible.value = true
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm.value, {
    id: null,
    username: '',
    realName: '',
    email: '',
    phone: '',
    status: 1,
    password: '',
    confirmPassword: ''
  })
}

// 保存用户
const saveUser = async () => {
  try {
    await userFormRef.value.validate()
    saveLoading.value = true
    
    if (isEdit.value) {
      // 编辑用户
      const response = await userApi.updateUser(userForm.value.id, userForm.value)
      if (response.data.code === 200) {
        ElMessage.success('用户更新成功')
        await loadUsers()
      } else {
        throw new Error(response.data.message || '用户更新失败')
      }
    } else {
      // 添加用户
      const response = await userApi.createUser(userForm.value)
      if (response.data.code === 200) {
        ElMessage.success('用户添加成功')
        await loadUsers()
      } else {
        throw new Error(response.data.message || '用户添加失败')
      }
    }
    
    userDialogVisible.value = false
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 删除用户
const deleteUser = async (userId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await userApi.deleteUser(userId)
    if (response.data.code === 200) {
      ElMessage.success('用户删除成功')
      await loadUsers()
    } else {
      throw new Error(response.data.message || '用户删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 显示角色分配对话框
const showRoleAssignDialog = async (user) => {
  currentUser.value = user
  selectedRoleIds.value = user.roles?.map(role => role.id) || []
  roleAssignDialogVisible.value = true
  
  // 如果还没有加载角色列表，则加载
  if (availableRoles.value.length === 0) {
    await loadAvailableRoles()
  }
}

// 分配角色
const assignRoles = async () => {
  if (!currentUser.value) return
  
  try {
    roleAssignLoading.value = true
    
    const response = await userApi.assignRoles(currentUser.value.id, selectedRoleIds.value)
    if (response.data.code === 200) {
      ElMessage.success('角色分配成功')
      // 更新本地用户数据
      currentUser.value.roles = availableRoles.value.filter(role => 
        selectedRoleIds.value.includes(role.id)
      )
      // 刷新用户列表
      await loadUsers()
      roleAssignDialogVisible.value = false
    } else {
      throw new Error(response.data.message || '角色分配失败')
    }
  } catch (error) {
    console.error('角色分配失败:', error)
    ElMessage.error(error.message || '角色分配失败')
  } finally {
    roleAssignLoading.value = false
  }
}

onMounted(() => {
  loadUsers()
  loadAvailableRoles()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>
